<template>
  <a-layout>
    <a-row type="flex" class="topline">
      <a-icon type="left" style="font-size:20px;position" @click="goback" />
      <div class="left2" style="cursor: pointer" @click="goback">返回</div>
      <h3>{{ pageTitle }}</h3>
      <a-icon type="add" />
    </a-row>
    <a-layout-content class="stepbox">
      <a-steps :current="current" @change="stepChange">
        <a-step title="选择模板" />
        <a-step title="确认合同内容" />
        <a-step title="预览合同发起签署" />
      </a-steps>
      <div v-if="current === 0">
        <div class="stepcontent" style="margin: 0; margin-top: 24px; min-height: auto; padding-bottom: 60px">
          <li>
            <p class="bleft">选择员工签署方</p>
            <a-row type="flex" class="licontent">
              <a-button type="text" @click="selectMember">{{ btnName }}</a-button>
              <a-col v-if="selectedList">
                <span>
                  已选择
                  <span class="nameStyle">{{
                    selectedList
                      .slice(0, 3)
                      .map((item) => item.name)
                      .join(",")
                  }}</span>
                  {{ " 等 " + selectedList.length + " 个人" }}
                </span>
                <span v-if="fold == true" class="fold" @click="fold = false">
                  收起
                  <a-icon type="arrow-up" />
                </span>
                <span v-if="fold == false" class="fold" @click="fold = true">
                  展开
                  <a-icon type="arrow-down" />
                </span>
              </a-col>
            </a-row>
            <a-table
              v-if="fold == true"
              :columns="memberColumn"
              :data-source="selectedList"
              :scroll="{ y: 320 }"
              row-key="id"
              size="small"
              style="margin-top: 12px; width: 100%"
            />
            <employee-select
              :show.sync="chooseMemberVisible"
              :default-selected-keys="defaultSelectedKeys"
              :selected-list.sync="selectedList"
              :template-id="templateId"
            />
          </li>
          <!-- <li>
            <div class="swtichFont">员工签署时，是否开始人脸识别</div>
            <a-switch checked-children="是" un-checked-children="否" :checked="isCheckFace" @change="onSwitchChange" />
          </li> -->
<!--          <li v-if="!personOnly">
            <p class="bleft">选择企业签署方</p>
            <a-input
              v-model="InfoDetail.enterpriseName"
              :placeholder="InfoDetail.enterpriseName"
              style="width: 260px; margin-top: 12px"
              disabled
            />
          </li>-->
          <li style="margin-bottom: 0">
            <p class="bleft">选择合同模板</p>
            <div class="boxlist">
              <div
                v-for="(temp, idx) in templist"
                :key="idx"
                class="choosebox"
                :class="templateId == temp.id ? 'addclass' : ''"
                @click="onClick(temp.id)"
              >
                <img src="../../../assets/img/hetong.png" alt />

                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ temp.name }}</span>
                  </template>
                  <span style="width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ getName(temp.name) }}</span>
                </a-tooltip>
              </div>
              <div v-if="templist.length === 0" class="choosebox">
                <p>
                  当前合同类型暂无合同模板，
                  <span class="primary_color" style="cursor: pointer" @click="toAddTemplate">去添加</span>
                </p>
              </div>
            </div>
          </li>
        </div>
        <div
          class="btnline bgc-white"
          :style="{
            position: 'fixed',
            width: 'auto',
            bottom: fixedBottom,
            right: '24px',
            zIndex: '10',
            left: fixedLeft
          }"
        >
          <a-button type="primary" @click="nextStep">下一步</a-button>
        </div>
      </div>
      <ConfirmContract
        ref="ConfirmContract"
        v-if="current === 1"
        :template-id="templateId"
        :enterprise-name="enterpriseName"
        :contractlist.sync="contractlist"
        :variableListMap.sync="variableListMap"
        @current="change"
      />
      <PreviewContract
        v-if="current === 2"
        :contractlist="contractlist"
        :contractinfo="InfoDetail"
        :variableListMap="variableListMap"
        :template-id="templateId"
        :isCheckFace="isCheckFace"
        @current="change"
      />
    </a-layout-content>
  </a-layout>
</template>
<script>
import { notification } from "ant-design-vue";
import { getCategoriesBycategoryId, getEmpInfoListForContract, templatesListAll } from "@/api/company/contract";
import { reviseCompanyName } from "./funcs";
import EmployeeSelect from "@/components/EmployeeSelect2/employeeSelect8";
import ConfirmContract from "./components/confirmContract";
import PreviewContract from "./components/previewContract";
import moment from "moment";
import { isContainByString } from "@/utils/index";
import { getSelectBySiteId } from "./api";
const memberColumn = [
  {
    title: "员工姓名",
    dataIndex: "name",
    align: "center",
    width: 200
  },
  {
    title: "部门",
    dataIndex: "depName",
    align: "center",
    width: 200,
    customRender: (text, row, index) => {
      return text != null ? text : "--";
    }
  },
  {
    title: "岗位",
    dataIndex: "positionName",
    align: "center",
    width: 200,
    customRender: (text, row, index) => {
      return text != null ? text : "--";
    }
  },
  {
    title: "证件号码",
    dataIndex: "idCard",
    align: "center",
    width: 250,
    customRender: (text, row, index) => {
      return text != null ? text : "--";
    }
  }
];
export default {
  components: { EmployeeSelect, ConfirmContract, PreviewContract },
  data() {
    return {
      isContainByString,
      memberColumn,
      pageTitle: "发起签署",
      isActive: -1,
      current: 0,
      enterpriseName: "",
      btnName: "选择员工",
      theCurrentCompany: this.$store.state.hr.companyName,
      chooseMemberVisible: false,
      chooseStaffVisible: false,
      postRules: {},
      personOnly: false,
      fold: false,
      InfoDetail: {},
      confirmList: [],
      contractlist: [],
      variableListMap: [],
      templist: [],
      selectedList: [],
      defaultSelectedKeys: [],
      templateId: null,
      fromLeave: false,
      enableCheckFace: true,
      isCheckFace: false
    };
  },
  computed: {
    fixedLeft() {
      const isOpened = this.$store.state.app.sidebar.opened;
      return `${isOpened ? 210 + 24 : 64 + 24}px`;
    },
    fixedBottom() {
      const mainWidth = this.$store.state.app.mainWidth;
      const isOpened = this.$store.state.app.sidebar.opened;
      const contentWidth = mainWidth - (isOpened ? 210 : 64) - 48;
      const isScrolling = contentWidth < 1000;
      return `${isScrolling ? 9 + 24 : 24}px`;
    }
  },
  watch: {
    contractlist(val) {
      const keys = this.contractlist.map((item) => item.id);
      this.selectedList = this.selectedList.filter((item) => keys.includes(item.id));
    }
  },
  created() {
    this.getInfoBycategoryId();
    this.getTemplatesListAll();
    // this.onGetSelectBySiteId();
    this.pageTitle = "发起合同";
    if (this.$route.query.fromLeave) {
      this.fromLeave = this.$route.query.fromLeave;
    }
    if (this.$route.query.leaveList) {
      this.selectedList = [];
      for (var i = 0; i < this.$route.query.leaveList.length; i++) {
        this.selectedList.push({
          depName: this.$route.query.leaveList[i].depName,
          id: this.$route.query.leaveList[i].empId ? this.$route.query.leaveList[i].empId : this.$route.query.leaveList[i].id,
          idCard: this.$route.query.leaveList[i].idCard,
          isSelected: true,
          name: this.$route.query.leaveList[i].empName ? this.$route.query.leaveList[i].empName : this.$route.query.leaveList[i].name,
          phone: this.$route.query.leaveList[i].phone,
          positionName: this.$route.query.leaveList[i].positionName
        });
      }
    }
  },
  methods: {
    getInfoBycategoryId() {
      getCategoriesBycategoryId(this.$route.query.id).then((res) => {
        this.InfoDetail = res.data;
        if (this.InfoDetail.signType === "person_only") {
          this.personOnly = true;
        } else {
          this.personOnly = false;
          console.log("===========",this.InfoDetail )
          this.enterpriseName = this.InfoDetail.enterpriseName;
        }
      });
    },
    // 获取选择的合同模板
    getTemplatesListAll() {
      templatesListAll({ categoryId: this.$route.query.id }).then((res) => {
        this.templist = res.data;
        if (this.templist.length > 0) {
          this.templateId = this.templist[0]["id"];
        }
        if (this.templist.length === 0) {
          notification.warning({
            message: "提示",
            description: "请前往合同类型管理添加合同模板"
          });
        }
      });
    },
    onChange(current) {
      this.current = current;
    },
    goback() {
      if (this.fromLeave) {
        this.$router.push({
          path: "/contract/type",
          query: {
            leaveList: this.selectedList,
            fromLeave: this.fromLeave
          }
        });
      } else {
        this.$router.go(-1);
      }
    },
    getName(name) {
      if (name.length > 10) {
        return name.substring(0, 9);
      } else {
        return name;
      }
    },
    toAddTemplate() {
      this.$router.push({
        path: "/contract/setting",
        query: { id: this.$route.query.id, current: "2" }
      });
    },
    nextStep() {
      if (this.templateId) {
        getEmpInfoListForContract({
          companyId: this.$store.state.hr.companyId,
          templateId: this.templateId,
          empIdList: this.selectedList.map((item) => item.id)
        })
          .then((res) => {
            // 字符串合同时间转 date类型
            res.data.forEach((item) => {
              if (item.contractStartTime) {
                item.contractStartTime = moment(item.contractStartTime, "YYYY-MM-DD");
              }
              if (item.contractEndTime) {
                item.contractEndTime = moment(item.contractEndTime, "YYYY-MM-DD");
              }
              if (item.contractExpire) {
                const ex = item.contractExpire.split(" ");
                item.contractExpire = parseInt(ex[0]);
                if (ex[1] === "年") {
                  item.timelimitType = 1;
                } else if (ex[1] === "月") {
                  item.timelimitType = 2;
                }
              }
            });
            this.contractlist = reviseCompanyName(res.data, this.enterpriseName, this.contractlist);
            this.current = 1;
          })
          .catch((err) => {
            console.log("debug log --> ", err);
          });
      } else {
        this.$message.warning("请选择合同模板");
      }
    },
    selectMember() {
      if (this.templateId) {
        this.chooseMemberVisible = true;
      } else {
        this.$message.warning("需要先选择合同模板");
      }
    },
    change(e) {
      this.current = e;
      if (e === 0) {
        this.selectedList = this.contractlist;
        this.defaultSelectedKeys = this.contractlist.map((item) => item.id.toString());
      }
    },
    onClick(id) {
      this.templateId = id;
    },
    stepChange(e) {
      if (e === 0) this.current = e;
      if (e === 1) this.nextStep();
      if (e === 2) {
        if (this.current === 0) {
          this.$message.warning("请先确合同内容");
        } else {
          this.$refs.ConfirmContract.nextStep();
        }
      }
    },
    async onGetSelectBySiteId() {
      try {
        const { data } = await getSelectBySiteId();
        this.enableCheckFace = data.enableCheckFace;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onSwitchChange(e) {
      if (this.enableCheckFace) {
        this.isCheckFace = e;
      } else {
        this.$notification.warning({ message: "暂无权限" });
        this.isCheckFace = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import url("./styles/initiateSign.scss");
</style>
